import { useState, useEffect, forwardRef, useImperativeHandle, useRef, useCallback } from "react";
import { Button, DatePicker, Col, Row, Space, Popover, Image, Typography, Form, InputNumber, message } from "antd";
import CommonTag from "@/components/CommonTag";
import { CommonModal } from "@/views/components/CommonModal";
import HeaderTab from "@/components/CommonTab/index";
import CustomizeGoodsModal from "./CustomizeGoodsModal";
import { getGoodsSkuPage, getGoodsSpuPage } from "../service";
import { SearchSimpleTable } from "@/views/components/SearchTable/index";
import CommonZjfImg from "@/views/components/CommonZjfImg";
import { Input, Select } from "@/views/components/PrefixPlaceholder";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import { NumText } from "@/pages/OrderModule/common/components/CommonText";
import {
	getArrayItem,
	SPU_STATUS,
	SPU_SYNC_STATUS,
	SPU_PRICE_TYPE,
	SPU_OTHER_ATTR,
	YES_NO_NUM_STATUS
} from "@/views/utils/constant";
const { Text } = Typography;
import moment from "moment";
import { cloneDeep, findIndex, set } from "lodash";
const { RangePicker } = DatePicker;
const dateFormat = "YYYY-MM-DD HH:mm:ss";

const tabArr = [
	//顶部tab信息
	{ key: "1", tab: "系统商品" },
	{ key: "2", tab: "自定义商品" }
];

const GoodsListModal = forwardRef(
	(
		{
			rowKey = "id",
			visible,
			handleCancel,
			storeList,
			onGoodsSkuListSelected,
			updateData,
			memberPricedisabled,
			memberPriceReadOnly,
			ids,
			isNotShow,  //是否展示组合商品 商品类型下拉不展示 默认选择单
			defaultNum,
			selectName,
			selectTitle,
			records,
			isExactMatch,
            matchOrNot, //新建退货出库单 选择商品默认查询的参数
			showCustomizeGoods = false, //是否展示自定义商品
			hiddenGoodNum = false, //是否隐藏商品数量
            hiddenExtra = false, //按款式隐藏多余的搜索条件和列
			...args
		},
		ref
	) => {

		const [isView, setIsView] = useState(false);
		const [isEdit, setIsEdit] = useState(false);
		const [isAdd, setIsAdd] = useState(false);
		const [type, setType] = useState("1"); //新增商品类型

		const customizeRef = useRef(null);

		useEffect(() => {
			setIsView(selectName == "search");
			setIsEdit(selectName == "update");
			setIsAdd(selectName == "add");
		}, [selectName]);
		const tableRequest = hiddenExtra ? getGoodsSpuPage: getGoodsSkuPage;
		const [columns] = useState([
			{
				name: "序号",
				code: "index",
				render: (t, r, i) => i + 1,
				lock: true,
				width: 60
			},
			{
				name: "图片",
				code: "image",
				width: 80,
				render: (value, record) => <Image width={60} src={value} />
			},
			{
				name: "款式编码",
				code: "spuCode",
				width: 160,
				formItemProps: {
					initialValue: records ? records.spuCode : ""
				},
				search: {
					order: 1,
					content: () => (
						<Input disabled={isEdit || isView} defaultValue={records ? records.spuCode : ""} placeholder="款式编码" />
					)
				}
			},
			{
				name: "商品编码",
				code: hiddenExtra ? "spuCode": "skuCode",
				width: 160,
				search: { hidden: hiddenExtra, order: 2, content: () => <Input defaultValue={records ? records.skuCode : ""} placeholder="商品编码" /> },
				render: (text, { type }) => {
					return (
						<>
							<div>{text}</div>
							{!isNotShow && type == 2 && <CommonTag type="zuhe" />}
						</>
					);
				}
			},
			{
				name: "商品名称",
				code: hiddenExtra ? "spuName": "skuName",
				searchCode: "skuNameOrCode",
				width: 300,
				search: { order: 3, content: () => <Input placeholder="商品名称" /> }
			},
			{
				name: "商品简称",
				code: "skuAbbreviation",
				width: 160,
				search: { order: 4, content: () => <Input placeholder="商品简称" /> }
			},
			{
				name: "颜色规格",
				code: "colorSpecifications",
                hidden: hiddenExtra,
				search: { order: 5, content: () => <Input placeholder="颜色及规格" /> }
			},
			{
				hidden: hiddenGoodNum,
				name: "数量",
				code: "num",
				render: (text, record, index) =>
					isView || hiddenGoodNum ? (
						text || 1
					) : (
						<InputNumber
							min={1}
							value={text}
							defaultValue={defaultNum}
							precision={0}
							onBlur={e => handleNumChange(e, record, index, "num")}
						/>
					)
			},
			{
				hidden: true,
				name: "商品类型",
				code: "type",
				width: 160,
				search: {
					order: 12,
					hidden: isNotShow || hiddenExtra,
					content: () => (
						<Select
							allowClear
							placeholder="商品类型"
                            defaultValue={isNotShow ? '1': undefined}
							options={[
								{
									label: "单商品2",
									value: '1'
								},
								{
									label: "组合",
									value: '2'
								}
							]}
						></Select>
					)
				}
			},
			{
				name: "零售价（元）",
				render: value => value && <NumText as="s1" pre="¥" num={value} />,
				code: "retailPrice",
				search: {
					span: 3,
					order: 13,
					content: () => (
						<Input.Group compact style={{ display: "flex" }}>
							<Form.Item name="priceType" noStyle>
								<Select
									origin
									placeholder="选择价格"
									options={SPU_PRICE_TYPE}
									style={{
										flex: 1
									}}
								/>
							</Form.Item>
							<Form.Item name="minPrice" style={{ textAlign: "center", flex: 1, marginBottom: 0 }}>
								<InputNumber
									min={0}
									placeholder="最小值"
									style={{
										textAlign: "center",
										flex: 1
									}}
								/>
							</Form.Item>
							<Input
								style={{
									width: 30,
									borderLeft: 0,
									borderRight: 0,
									pointerEvents: "none"
								}}
								placeholder="-"
								disabled
							/>
							<Form.Item name="maxPrice" style={{ textAlign: "center", flex: 1, marginBottom: 0 }}>
								<InputNumber
									min={0}
									placeholder="最大值"
									style={{
										textAlign: "center",
										flex: 1
									}}
								/>
							</Form.Item>
						</Input.Group>
					)
				}
			},
			{
				name: "采购价（元）",
				code: "purchasePrice",
				render: value => value && <NumText as="s1" pre="¥" num={value} />,
				search: {
					order: 14,
					span: 3,
					group: [
						{
							span: 12,
							code: "attributeType",
							content: () => <Select placeholder="其他属性" origin options={SPU_OTHER_ATTR} className="width-full" />
						},
						{
							span: 12,
							code: "attribute",
							content: () => <Input placeholder="请输入" />
						}
					]
				}
			},
			{
				name: "成本价（元）",
				code: "costPrice",
				render: value => value && <NumText as="s1" pre="¥" num={value} />
			},
			{
				name: "市场价|吊牌价（元）",
				code: "tagPrice",
				width: 160,
				render: value => value && <NumText as="s1" pre="¥" num={value} />
			},
			{ name: "可用库存", code: "availableInventory" },
			{ name: "虚拟库存", code: "virtualInventory" },
			{
				name: "库存同步状态",
				code: "syncStatus",
				render: value => getArrayItem(SPU_SYNC_STATUS, value).label
			},
			{
				name: "重量(kg)",
				code: "weight",
				width: 90,
				render: value => value && <NumText as="s1" suffix="kg" num={value} />
			},
			{
				name: "状态",
				hidden: isNotShow,
				code: "status",
				render: value => <Text type={getArrayItem(SPU_STATUS, value)?.type}>{getArrayItem(SPU_STATUS, value)?.label}</Text>,
				search: {
					order: 9,
					hidden: isNotShow || hiddenExtra,
					content: () => (
						<Select
							options={[
								...SPU_STATUS,
								{
									label: "全部",
									value: null
								}
							]}
							placeholder="商品状态"
						></Select>
					)
				}
			},
			{ name: "商品备注", code: "note" },
			{
				name: "创建时间",
				code: "createTime",
				width: 180,
				render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
				search: {
					order: 180,
					span: 6,
					group: [
						{
							span: 6,
							code: "dateType",
							content: () => (
								<Select className="width-full" origin placeholder="选择日期" allowClear>
									<Option value={1}>修改日期</Option>
									<Option value={2}>创建日期</Option>
									<Option value={3}>最后同步日期</Option>
								</Select>
							)
						},
						{
							keys: ["startTime", "endTime"],
							span: 18,
							code: "time",
							content: () => <RangePicker format={dateFormat} showTime />
						}
					]
				}
			},
			{
				name: "最后修改时间",
				code: "updateTime",
				width: 180,
				render: text => (text ? <div>{moment(text).format("YYYY-MM-DD HH:mm:ss")}</div> : ""),
				search: { hidden: hiddenExtra, code: "supplierSpuCode", order: 7, content: () => <Input placeholder="供应商款式编码" /> }
			},
			{
				name: "会员价",
				code: "memberPrice",
				render: (text, record, index) => {
					if (memberPriceReadOnly) {
						return text;
					} else {
						return (
							<InputNumber
								disabled={memberPricedisabled}
								min={1}
								value={text}
								precision={0}
								onBlur={e => handleNumChange(e, record, index, "price")}
							/>
						);
					}
				}
			},
			{
				name: "商品匹配(精准匹配)",
				code: "goodsSkuMatches1",
				width: 250,
				hidden: memberPricedisabled ? false : true,
				render: (text, record, index) => {
					return (
						<Select
							origin
							onChange={e => changeSkuMatches(e, record)}
							style={{ width: "100%" }}
							options={record.goodsSkuMatches?.map(item => {
								return {
									...item,
									label: item.supplierName,
									value: item.id
								};
							})}
						/>
					);
				}
			},
			{
				name: "商品匹配",
				code: "note",
				width: 400,
				hidden: memberPricedisabled ? true : false,
				render: (_, record) => {
					if (record.goodsSkuMatches1)
						return (
							<Popover>
								{(record.goodsSkuMatches || []).map((item, i) => {
									if (item.id == record.goodsSkuMatches1)
										return (
											<p key={i + item.id} style={{ lineHeight: "16px" }}>
												{item.supplierName}*{item.supplierSpuCode}*{item.supplierSkuName}*{item.supplierSkuCode}
												{item.isDefault && "（默认）"}
											</p>
										);
								})}
							</Popover>
						);
					return (
						<Popover>
							{(record.goodsSkuMatches || []).map((item, i) => {
								return (
									<p key={i + item.id} style={{ lineHeight: "16px" }}>
										{item.supplierName}*{item.supplierSpuCode}*{item.supplierSkuName}*{item.supplierSkuCode}
										{item.isDefault && "（默认）"}
									</p>
								);
							})}
						</Popover>
					);
				},
				search: {
                    hidden: hiddenExtra,
					code: "isManyGoods",
					order: 11,
					content: () => <Select options={YES_NO_NUM_STATUS} placeholder="是否多个商品匹配" />
				}
			},
			{
				name: "供应商商品图片",
				code: "supplierSkuImage",
				width: 90,
				render: (_, record) => {
					return (
						<CommonZjfImg img={record.supplierSkuImage} storeId={record.supplierId} style={{ width: "48px", height: "48px" }} />
					);
				}
			},
			{
				hidden: true,
				name: "供应商名称",
				code: "supplierName",
				width: 160,
				search: { hidden: hiddenExtra, order: 6, content: () => <Input placeholder="供应商名称" /> }
			},
			{
				name: "供应商商品名称",
				code: "supplierSkuName",
				width: 130,
				search: { hidden: hiddenExtra, code: "supplierSkuCode", order: 8, content: () => <Input placeholder="供应商商品编码" /> }
			},
			{
				name: "供应商颜色规格",
				code: "supplierSkuSpecs",
				width: 130,
				search: {
                    hidden: hiddenExtra,
					code:  "isMatch",
					order: 10,
					content: () => <Select options={YES_NO_NUM_STATUS} placeholder="是否仅匹配供应商" />
				}
			}
		]);
		const onOk = () => {
			if (selectedAllPagesRows.current.length > 0) {
				if (records) {
					updateData(records);
				}
				dataSource?.forEach(i => {
					selectedAllPagesRows.current?.forEach(j => {
						if (i.id === j.id) {
							j.goodsSkuMatches1 = i.goodsSkuMatches1;
						}
					});
				});
				onGoodsSkuListSelected(selectedAllPagesRows.current);
				onCancel();
			} else {
				message.error("请选择商品");
			}
		};

		//自定义商品的提交
		const onCustomizeOk = () => {
			const arr = customizeRef.current.customizeList;
			const newArr = [];
			const goodsNameIndex = findIndex(arr, ["goodsName", ""]);
			const goodsNumIndex = findIndex(arr, ["goodsNum", ""]);
			const storeIdIndex = findIndex(arr, ["storeId", ""]);
			// const shopCodeIndex = findIndex(arr, ["shopCode", ""]);
			const goodsPriceIndex = findIndex(arr, ["goodsPrice", ""]);
			if (goodsNameIndex > -1) {
				return message.info("商品名称不能为空");
			}
			if (goodsNumIndex > -1) {
				return message.info("商品数量不能为空");
			}
			if (storeIdIndex > -1) {
				return message.info("供应商不能为空");
			}
			// if (shopCodeIndex > -1) {
			// 	return message.info("档口号不能为空");
			// }
			if (goodsPriceIndex > -1) {
				return message.info("采购价不能为空");
			}
			arr.forEach(item => {
				newArr.push({
					...item,
					customType: 2,
					storeCode: item.shopCode, //档口号
					sysGoodsImage: item.goodsImage,
					sysGoodsName: item.goodsName,
					sysGoodsPrice: item.goodsPrice,
					sysGoodsSpec: item.size + item.color
				});
			});
			if (records) {
				updateData(records);
			}
			onGoodsSkuListSelected(newArr, true);
			onCancel();
		};

		const [formModal] = Form.useForm();
		const selectionChange = useCallback((__selectedRowKeys, __selectedRows) => {
			setInputValueByRows(__selectedRows);
		}, []);

		function setInputValueByRows(__selectedRows) {
			const v = (__selectedRows || []).map(e => `${e.skuCode}*${e.num || 1}`).join(",");
			formModal.setFieldValue("inputValue", v);
		}
		const onCancel = () => {
			handleCancel();
			formModal.resetFields();
		};
		const changeSkuMatches = (e, record) => {
			updateDataSource(pre => {
				const arr = cloneDeep(pre);
				arr.forEach((element, i) => {
					if (element.id == record.id) {
						element.goodsSkuMatches1 = e;
					}
					return element;
				});
				return arr;
			});
		};

		const tableKey = "GoodsListModal123213";
		const {
			RefTable,
			fetchList,
			selectedRows,
			selectedAllPagesRows,
			searchSimpleTableProps,
			dataSource,
			form,
			query,
			updateSearchQuery,
			updateDataSource
		} = useTableConfig({
			tableKey,
			rowKey,
			keepSelected: true,
			columns,
			tableRequest,
			pageSize: 50,
			pageSizeOptions: [50, 100, 200, 500],
			autoFetch: false,
			hasPagination: true,
			hasQuickSearch: false,
			beforeQuerySearch: ({ API_DATA }) => {
				if (selectName == "update") {
					API_DATA.spuCode = records.spuCode;
				}
				if (isNotShow) {
					API_DATA.type = 1;
				}
				// 是否为精准匹配1是0否
				if (isExactMatch) {
					API_DATA.isExactMatch = isExactMatch;
				}
                if(matchOrNot) {
					API_DATA.matchOrNot = matchOrNot;
                }
				if (selectName == "search") {
					API_DATA.spuCode = records.spuCode;
					API_DATA.skuCode = records.skuCode;
				}
				return {
					...API_DATA
					// type: 1
				};
			},
			resetSourceData: false,
			hasColsSetting: false,
			hasToggleSearchForm: true,
			columnResize: true,
			selectionChange
		});
		useEffect(() => {
			if (selectName == "search") {
				updateSearchQuery({ spuCode: records.spuCode, skuCode: records.skuCode });
				form.setFieldValue("skuCode", records.skuCode);
				form.setFieldValue("spuCode", records.spuCode);
				fetchList({ spuCode: records.spuCode, skuCode: records.skuCode });
			} else if (selectName == "update") {
				updateSearchQuery({ spuCode: records.spuCode });
				fetchList({ spuCode: records.spuCode });
				form.setFieldValue("spuCode", records.spuCode);
			} else {
				fetchList();
			}
		}, []);
		function filterUniqueById(items) {
			return items.reduce((accumulator, item) => {
				if (!accumulator.some(accItem => accItem.id === item.id)) {
					accumulator.push(item);
				}
				return accumulator;
			}, []);
		}
		// function resetSourceData(d) {
		// 	const list = [...d, ...selectedAllPagesRows.current];
		// 	const filterList = filterUniqueById(list);
		// 	return filterList;
		// }
		const handleNumChange = (e, record, index, type) => {
			const reg = /^[1-9]\d*$/;
			const val = e.target.value;

			if (reg.test(val)) {
				if (type === "num") {
					updateDataSource(pre => {
						const arr = cloneDeep(pre);
						let list = [];
						arr.forEach((element, i) => {
							if (element.id == record.id) {
								element.num = val;
								selectedAllPagesRows.current.forEach(j => {
									if (j.id == element.id) {
										j.num = element.num;
										list.push(element);
									}
								});
							}
							return element;
						});
						const v = (selectedAllPagesRows.current || []).map(e => `${e.skuCode}*${e.num || 1}`).join(",");

						formModal.setFieldValue("inputValue", v);
						return arr;
					});
				} else {
					updateDataSource(pre => {
						const arr = cloneDeep(pre);
						let list = [];
						arr.forEach((element, i) => {
							if (element.id == record.id) {
								element.memberPrice = val;
								selectedAllPagesRows.current.forEach(j => {
									if (j.id == element.id) {
										j.memberPrice = element.memberPrice;
										list.push(element);
									}
								});
							}
							return element;
						});
						return arr;
					});
				}
			} else {
				message.info("请输入正整数");
			}
		};

		const handlePressChange = async inputValue => {
			const str = String(inputValue).replace(/\s+/g, "");
			const arr = str.split(/[,，]/).map(text => {
				const arr1 = text.split("*");
				return {
					skuCode: arr1[0] || "", //默认为空
					num: arr1[1] || 1 //默认为1
				};
			});
			//更新数据
			updateDataSource(pre => {
				const __pre = cloneDeep(pre);
				const ids = [];
				__pre.map((row, i) => {
					// 根据 skuCode查找
					const f = arr.find(e => e.skuCode == row.skuCode);
					if (f && f.skuCode) {
						//更新数量
						row.num = f.num;
						//收集回显id
						ids.push(row[rowKey]);
					}

					return cloneDeep(row);
				});
				//需要在updateDataSource更新后，执行回显方式
				setTimeout(() => {
					RefTable?.current?.setTableSelect?.(ids);
					if (isView) formModal.setFieldValue("inputValue", inputValue); // 查看模式下，无checkbox，不会执行setTableSelect、所以需要手动回显inputValue
				}, 10);
				return __pre;
			});
		};
		const commonPressEnter = async inputValue => {
			//RefTable?.current?.clearTableSelected();

			//去空格
			const str = String(inputValue).replace(/\s+/g, "");
			const arr = str.split(/[,，]/).map(text => {
				const arr1 = text.split("*");
				return {
					skuCode: arr1[0] || "", //默认为空
					num: arr1[1] || 1 //默认为1
				};
			});
			//更新数据
			updateDataSource(pre => {
				const __pre = cloneDeep(pre);
				const ids = [];
				__pre.map((row, i) => {
					// 根据 skuCode查找
					const f = arr.find(e => e.skuCode == row.skuCode);
					if (f && f.skuCode) {
						//更新数量
						row.num = f.num;
						//收集回显id
						ids.push(row[rowKey]);
					}

					return cloneDeep(row);
				});
				//需要在updateDataSource更新后，执行回显方式
				setTimeout(() => {
					RefTable?.current?.setTableSelect?.(ids);
					if (isView) formModal.setFieldValue("inputValue", inputValue); // 查看模式下，无checkbox，不会执行setTableSelect、所以需要手动回显inputValue
				}, 10);
				return __pre;
			});
		};
		const leftBtns = (
			<Space>
				<Button style={{ display: false }}></Button>
			</Space>
		);
		useEffect(() => {}, [selectedRows]);
		useImperativeHandle(ref, () => ({
			// 暴露给父组件的方法
			RefTable: RefTable.current,
			name: "GoodsListModal",
			...(RefTable.current || {}),
			commonPressEnter,
			handleFocusChange: commonPressEnter
		}));
		function extractNumbers(data) {
			console.log(data, "data");
			const items = data.split(",");
			const numbers = items
				.map(item => {
					const match = item.match(/\d{9}/);
					return match ? match[0] : null;
				})
				.filter(Boolean); // Filter out any null values
			console.log(numbers, "numbers");
			return numbers?.join(",");
		}
		console.log(selectedAllPagesRows, "selectedAllPagesRows");
		const getSearchFormVal = useCallback(() => {
			console.log(formModal.getFieldValue("inputValue"), "formModal");
			const skuCode = selectedAllPagesRows?.current?.map(x => x.skuCode)?.join(",");
			form.setFieldValue("skuCode", skuCode);
			return {
				search: { skuCode: skuCode },
				allPagesSelected: selectedAllPagesRows.current
			};
		}, []);
		//顶部tab
		const HeaderTabProps = {
			type,
			data: tabArr,
			onChange(val) {
				setType(val);
			}
		};

		return (
			<CommonModal
				{...args}
				className="views-table-dialog"
				title={{ title: isEdit ? "编辑商品" : isAdd ? "新增商品" : selectTitle ? selectTitle : "" }}
				visible={true}
				width="1400px"
				onOk={onOk}
				onCancel={handleCancel}
				footer={
					type == "1" ? (
						<div style={{ display: "flex", justifyContent: "space-between" }}>
							<Row style={{ width: "1200px" }}>
								<Col span={24}>
									<Form form={formModal}>
										<Form.Item name="inputValue" label="">
											<Input
												readOnly={isView}
												onPressEnter={e => commonPressEnter(e.target.value)}
												onBlur={e => handlePressChange(e.target.value)}
											/>
										</Form.Item>
									</Form>
								</Col>
							</Row>
							<Row>
								<Col>
									<Space>
										<Button size="middle" onClick={onCancel}>
											取消
										</Button>
										{!isView && (
											<Button size="middle" type="primary" onClick={onOk}>
												确定
											</Button>
										)}
									</Space>
								</Col>
							</Row>
						</div>
					) : (
						<div style={{ textAlign: "right" }}>
							<Button size="middle" onClick={onCancel}>
								取消
							</Button>
							{!isView && (
								<Button size="middle" type="primary" onClick={onCustomizeOk}>
									确定
								</Button>
							)}
						</div>
					)
				}
			>
				{showCustomizeGoods ? <HeaderTab {...HeaderTabProps} /> : ""}
				{type == "1" ? (
					<div className="views-container">
						<SearchSimpleTable
							type={isView ? "simple" : "checkbox"}
							showMoreAction
							key={tableKey}
							leftBtns={leftBtns}
							mounted={false}
							getSearchFormVal={getSearchFormVal}
							{...searchSimpleTableProps}
						/>
					</div>
				) : (
					<CustomizeGoodsModal ref={customizeRef} />
				)}
			</CommonModal>
		);
	}
);

export default GoodsListModal;
